package com.lyw.forum.service.impl;

import com.lyw.forum.common.enums.ResultCode;
import com.lyw.forum.common.exception.ApplicationException;
import com.lyw.forum.common.utils.BeanTransUtils;
import com.lyw.forum.common.utils.SetDefaultUtils;
import com.lyw.forum.mapper.ArticleMapper;
import com.lyw.forum.pojo.dataobject.Article;
import com.lyw.forum.pojo.request.ArticleCreateRequest;
import com.lyw.forum.pojo.request.ArticleUpdateRequest;
import com.lyw.forum.pojo.response.AppResult;
import com.lyw.forum.pojo.response.ArticleSelectResponse;
import com.lyw.forum.pojo.response.BoardSelectResponse;
import com.lyw.forum.pojo.response.UserSelectResponse;
import com.lyw.forum.service.IArticleService;
import com.lyw.forum.service.IBoardService;
import com.lyw.forum.service.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;

    @Override
    public void creat(ArticleCreateRequest articleCreateRequest) {
        //转化
        Article articleRequest = BeanTransUtils.transArticleCreateRequest(articleCreateRequest);

        //设置默认值 减少数据库性能的开销
        Article article = SetDefaultUtils.setArticleRequestDefault(articleRequest);

        //写入数据库
        int result = articleMapper.insert(article);
        if (result <= 0) {
            //打印日志
            log.error(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        try {
            //更新用户的发帖数量
            userService.addOneArticleCountById(article.getUserId());
        } catch (ApplicationException e) {
            log.error(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }

        try {
            //更新板块的帖子数量
            boardService.addOneArticleCountById(article.getBoardId());
        } catch (ApplicationException e) {
            log.error(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        // 打印日志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");
    }

    @Override
    public List<ArticleSelectResponse> selectAll() {

        //调用mapper查询结果
        List<Article> articles = articleMapper.selectAll();

        //转换结果
        List<ArticleSelectResponse> articleSelectResponses = BeanTransUtils.transArticle(articles);

        //返回结果
        return articleSelectResponses;

    }

    @Override
    public List<ArticleSelectResponse> selectAllByBoardId(Integer BoardId) {
        //判断板块是否存在
        BoardSelectResponse boardSelectResponse = boardService.selectById(BoardId);
        if (boardSelectResponse == null) {
            //打印日志
            log.error(ResultCode.FAILED_BOARD_NOT_EXISTS + ", boardId: " + BoardId);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        //调用mapper查询结果
        List<Article> articles = articleMapper.selectAllByBoardId(BoardId);

        //转换结果
        List<ArticleSelectResponse> articleSelectResponses = BeanTransUtils.transArticle(articles);

        //返回结果
        return articleSelectResponses;

    }

    @Override
    public ArticleSelectResponse selectDetailById(Integer id) {
        //调用mapper查询结果
        Article article = articleMapper.selectDetailById(id);

        //判断结果是否为空
        if (article == null) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //更新帖子的访问次数
        Article articleUpdate = new Article();
        articleUpdate.setId(article.getId());
        articleUpdate.setVisitCount(article.getVisitCount() + 1);

        //调用mapper更新结果
        int result = articleMapper.updateById(articleUpdate);
        if (result != 1) {
            //打印日志
            log.error(ResultCode.ERROR_SERVICES + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        //转换
        ArticleSelectResponse articleSelectResponse = BeanTransUtils.transArticle(article);

        //更新返回对象的访问次数
        articleSelectResponse.setVisitCount(article.getVisitCount() + 1);

        return articleSelectResponse;
    }

    @Override
    public void modify(ArticleUpdateRequest articleUpdateRequest) {
        //转换
        Article article = BeanTransUtils.transArticleUpdateRequest(articleUpdateRequest);

        //设置更新时间
        article.setUpdateTime(new Date());

        //调用mapper更新结果
        int result = 0;
        try {
            result = articleMapper.updateById(article);
        } catch (Exception e) {
            log.error(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        if (result != 1) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS + ", id: " + article.getId());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

    }

    @Override
    public ArticleSelectResponse selectById(Integer id) {
        //调用mapper查询结果
        Article article = articleMapper.selectById(id);

        //转换结果
        ArticleSelectResponse articleSelectResponse = BeanTransUtils.transArticle(article);

        //返回结果
        return articleSelectResponse;
    }

    /**
     * 点赞
     * @param id 帖子id
     */
    @Override
    public void thumbsUpById(Integer id) {
        //获取帖子详情
        Article article = articleMapper.selectById(id);

        if (article == null || article.getDeleteState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if (article.getState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_BANNED + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //构建要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        //调用mapper更新结果
        int result = 0;
        try {
            result = articleMapper.updateById(updateArticle);
        } catch (Exception e) {
            log.error(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        if (result != 1) {
            //打印日志
            log.error(ResultCode.ERROR_SERVICES + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void deleteById(Integer id) {
        //根据id查询帖子信息
        Article article = articleMapper.selectById(id);

        if (article == null || article.getDeleteState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);

        //调用mapper更新结果
        int result = 0;
        try {
            result = articleMapper.updateById(updateArticle);
        } catch (Exception e) {
            //打印日志
            log.error(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        if (result != 1) {
            //打印日志
            log.error(ResultCode.ERROR_SERVICES + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        //更新板块中的帖子数量
        boardService.subOneArticleCountById(article.getBoardId());

        //更新用户中的帖子数量
        userService.subOneArticleCountById(article.getUserId());

        //打印日志
        log.info("删除帖子成功, ArticleId: " + id + ", userId: " + article.getUserId() + ", boardId: " + article.getBoardId());
    }

    @Override
    public void addOneReplyCountById(Integer id) {
        //获得帖子记录
        Article article = articleMapper.selectById(id);

        //校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS + ", articleId: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //帖子被封
        if (article.getState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_BANNED + ", articleId: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //构建要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());

        //调用mapper更新结果
        int result = 0;
        try {
            result = articleMapper.updateById(updateArticle);
        } catch (Exception e) {
            log.error(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        if (result != 1) {
            //打印日志
            log.error(ResultCode.ERROR_SERVICES + ", articleId: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<ArticleSelectResponse> selectByUserId(Integer id) {
        //校验用户是否存在
        UserSelectResponse userSelectResponse = userService.selectById(id);

        if (userSelectResponse == null) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS + ", id: " + id);
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //调用mapper
        List<Article> articles = articleMapper.selectByUserId(id);

        //转换
        List<ArticleSelectResponse> articleSelectResponses = BeanTransUtils.transArticle(articles);

        //返回结果
        return articleSelectResponses;
    }

}
